from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from account.serializer import UserForeignKeySer
from answer.models import Answer, AuestionPicture, AnswerPraiseRelationship, AnswerFocus
from questions.models import Question

User = get_user_model()


class PictureSer(serializers.ModelSerializer):
    class Meta:
        model = AuestionPicture
        fields = (
            'image',
        )


class AnswerCreateSer(serializers.ModelSerializer):
    # be referenced
    creator = UserForeignKeySer(
        default=serializers.CurrentUserDefault()
    )
    question_id = serializers.IntegerField(write_only=True)
    pictures = PictureSer(many=True, read_only=True)
    class Meta:
        model = Answer
        validators = [
            UniqueTogetherValidator(
                queryset=Answer.objects.all(),
                fields=('creator', 'question_id')
            )
        ]
        fields = (
            'id',
            'content',
            'praise',
            'created_time',
            'pictures',

            # foreign key
            'creator',
            'question_id',
        )

    def create(self, validated_data):
        question_id = validated_data.pop('question_id', None)
        picture_str = self.context['request'].data.get('pictures', None)

        picture_list = []
        if picture_str:
            for i in picture_str.split(" "):
                img = AuestionPicture.objects.create(image=i)
                picture_list.append(img)

        if question_id:
            try:
                question = Question.objects.get(id=question_id)
                answer = Answer.objects.create(question=question, **validated_data)
                answer.pictures.set(picture_list)
                answer.save()
                return answer
            except Question.DoesNotExist:
                raise serializers.ValidationError('question_id is invalid')
            pass
        else:
            raise serializers.ValidationError('question_id is required')


class AnswerUpdateSer(serializers.ModelSerializer):
    pictures = PictureSer(many=True, read_only=True)
    class Meta:
        model = Answer
        fields = (
            'id',
            'content',
            'pictures',
        )

    def update(self, instance, validated_data):
        picture_str = self.context['request'].data.get('pictures', None)
        picture_list = []
        if picture_str:
            for i in picture_str.split(" "):
                img = AuestionPicture.objects.create(image=i)
                picture_list.append(img)
        instance.pictures.set(picture_list)
        instance.save()
        super().update(instance, validated_data)
        return instance


class AnswerDetailSer(serializers.ModelSerializer):
    pictures = PictureSer(many=True, read_only=True)
    creator = UserForeignKeySer()
    is_praised = serializers.SerializerMethodField()
    is_focused = serializers.SerializerMethodField()

    def get_is_praised(self, obj):
        user = self.context['request'].user
        try:
            arl = AnswerPraiseRelationship.objects.get(answer=obj, user=user)
        except AnswerPraiseRelationship.DoesNotExist:
            arl = AnswerPraiseRelationship.objects.create(answer=obj, user=user)
        return arl.praise

    def get_is_focused(self, obj):
        user = self.context['request'].user
        if AnswerFocus.objects.filter(creator=user, answer=obj).exists():
            return True
        else:
            return False

    class Meta:
        model = Answer
        fields = (
            'id',
            'content',
            'praise',
            'pictures',
            'is_praised',
            'is_focused',
            'created_time',

            # foreign key
            'creator',
            'question',
            'comments',
        )


class AnswerForeignKeySer(serializers.ModelSerializer):
    pictures = PictureSer(many=True, read_only=True)
    class Meta:
        model = Answer
        fields = (
            'id',
            'content',
            'praise',
            'pictures',
            'created_time',
        )


class AnswerTrueSer(AnswerDetailSer):
    def get_is_praised(self, obj):
        return True
    def get_is_focused(self, obj):
        return False


class AnswerFalseSer(AnswerDetailSer):
    def get_is_praised(self, obj):
        return False
    def get_is_focused(self, obj):
        return False


class AnswerFocusCreateSer(serializers.ModelSerializer):
    creator = UserForeignKeySer(
        default=serializers.CurrentUserDefault()
    )
    answer = AnswerForeignKeySer(read_only=True)
    class Meta:
        model = AnswerFocus

        fields = ('id', 'answer', 'creator')


class AnswerFocusListSer(serializers.ModelSerializer):

    answer = AnswerForeignKeySer(read_only=True)

    class Meta:
        model = AnswerFocus
        fields = ('id', 'answer')